import api from "@/api";
import type { DictionaryModel } from "@/types";
import { create } from "zustand";
import { createJSONStorage, devtools, persist } from "zustand/middleware";

interface DictionaryState {
	dictionary: Map<string, DictionaryModel[]>;
	get: (key: string) => Promise<DictionaryModel[]>;
	set: (key: string, value: DictionaryModel[]) => void;
}

export const useDictionaryStore = create<DictionaryState>()(
	devtools(
		persist(
			(set, get) => ({
				dictionary: new Map<string, DictionaryModel[]>(),
				get: async (key: string) => {
					const d = get().dictionary;
					if (d.has(key)) return Promise.resolve(d.get(key) || []);

					return api
						.baseDictionaryGetDictionaryCreate({ module: key })
						.then((response) => {
							const moduleData = response.map(
								(x) =>
									({
										text: x.text || "",
										value: x.value || null,
									}) satisfies DictionaryModel,
							);
							set({ dictionary: d.set(key, moduleData) });
							return moduleData;
						});
				},
				set: (key: string, value: DictionaryModel[]) => {
					set({ dictionary: get().dictionary.set(key, value) });
				},
			}),
			{
				name: "dictionary",
				storage: createJSONStorage(() => sessionStorage),
			},
		),
	),
);
